/**
 * ConfigLocator.java
 */
package org.dicr.util.resource;

import java.io.*;
import java.net.*;

/**
 * Configuration resources locator. Find configuration as filename or resource in classpath.
 * 
 * @author <A href='http://dicr.org'>Igor A Tarasov</A>
 * @version 060503
 */
public class ConfigLocator {

	/**
     * Return file or resource with given name. First check of file existence with the given name, then, if file not
     * exists, locate resource with the given name in classpath.
     * 
     * @param name name of file or resource.
     * @return url of the file or resource or <code>null</code> if not found.
     */
	public static URL getResourceURL(final String name) {
		if (name == null) { throw new IllegalArgumentException("null name"); }
		URL url = null;
		final File file = new File(name);
		if (file.exists()) {
			try {
				url = file.toURI().toURL();
			} catch (final MalformedURLException ex) {
				// ignore
			}
		} else {
			url = ClassLoader.getSystemResource(name);
		}
		return url;
	}

	/**
     * Locate URL of file or resource with given name. It's call {@link #getResourceURL(String)} with the given name,
     * and if not found, prepend to name first "META-INF/${name}" and then "etc/${name}"
     * 
     * @param name name of file or resource.
     * @return resource or file url or <code>null</code> if not found.
     * @see #getResourceURL(String)
     */
	public static URL findResourceURL(final String name) {
		if (name == null) { throw new IllegalArgumentException("null name"); }
		URL url = ConfigLocator.getResourceURL(name);
		if (url == null) {
			url = ConfigLocator.getResourceURL("META-INF/" + name);
		}
		if (url == null) {
			url = ConfigLocator.getResourceURL("etc/" + name);
		}
		return url;
	}
}
